package com.bw.task.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bw.library.mvp.view.BaseFragment;
import com.bw.task.R;
import com.bw.task.adapter.MyLinearLayoutManager;
import com.bw.task.adapter.MyStandardGSYVideoPlayer;
import com.bw.task.adapter.MyVodioAdapter;
import com.bw.task.bean.ImgBean;
import com.bw.task.bean.MoneyBean;
import com.bw.task.bean.PopupWindioBean;
import com.bw.task.bean.UserBean;
import com.bw.task.bean.Vodiobean;
import com.bw.task.db.DaoMaster;
import com.bw.task.db.DaoSession;
import com.bw.task.db.User;
import com.bw.task.db.UserDao;
import com.bw.task.mvp.contern.UserContent;
import com.bw.task.mvp.contern.UserContentThree;
import com.bw.task.mvp.model.UserModel;
import com.bw.task.mvp.model.UserModelThree;
import com.bw.task.mvp.persenter.UserPersenter;
import com.bw.task.mvp.persenter.UserPersenterThree;
import com.bw.task.user.login.LoginActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.shuyu.gsyvideoplayer.GSYVideoManager;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.InputStream;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import master.flame.danmaku.controller.DrawHandler;
import master.flame.danmaku.danmaku.loader.ILoader;
import master.flame.danmaku.danmaku.loader.IllegalDataException;
import master.flame.danmaku.danmaku.loader.android.DanmakuLoaderFactory;
import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.DanmakuTimer;
import master.flame.danmaku.danmaku.model.IDanmakus;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;
import master.flame.danmaku.danmaku.parser.IDataSource;
import master.flame.danmaku.ui.widget.DanmakuView;


public class ThreeFragment extends BaseFragment<UserPersenterThree> implements UserContentThree.mView, OnRefreshLoadMoreListener, OnRefreshListener, UserContent.mView {
    private static final String TAG = "ThreeFragment";
    private UserPersenter mpersentermoney;
    private ImageView lw;
    List<PopupWindioBean.DataBean> data;
    boolean ispopu;
    int path = 1;
    private ImageView threeImg;
    private RecyclerView recyclerthree;
    private SmartRefreshLayout smart;
    List<Vodiobean.DataBean> datavodio;
    MyVodioAdapter myVodioAdapter;
    UserDao userDao;
    String uid;
    SharedPreferences user;
    private EditText textdm;
    private Button buttondm;
    private DanmakuContext mDanmakuContext;
    private DanmakuView dammu;
    private BaseDanmakuParser mParser;//解析器对象

    @Override
    public int bandLayout() {
        return R.layout.fragment_three;
    }

    @Override
    public void initData() {
        mpersentermoney = new UserPersenter(this, new UserModel());

        user = getActivity().getSharedPreferences("user", Context.MODE_PRIVATE);

        uid = user.getString("userid", "");
        LogUtils.i("-----礼物界面获取钱数id" + uid);
        /**
         * 数据库
         */
        DaoMaster.DevOpenHelper users = new DaoMaster.DevOpenHelper(getContext(), "usera");
        SQLiteDatabase writableDatabase = users.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(writableDatabase);
        DaoSession daoSession = daoMaster.newSession();
        userDao = daoSession.getUserDao();
//------------------------------------------------------------------------------------------------------------------
        buttondm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String trim = textdm.getText().toString().trim();
                addDanmaku(true,trim);
//                textdm.setText("");
            }
        });
        mDanmakuContext = DanmakuContext.create();
        mParser=new BaseDanmakuParser() {
            @Override
            protected IDanmakus parse() {
                return new Danmakus();
            }
        };
        dammu.prepare(mParser,mDanmakuContext);
        if (dammu != null) {
            dammu.setCallback(new DrawHandler.Callback() {
                @Override
                public void updateTimer(DanmakuTimer timer) {
                }

                @Override
                public void drawingFinished() {

                }

                @Override
                public void danmakuShown(BaseDanmaku danmaku) {
                }

                @Override
                public void prepared() {
                    dammu.start();

                }
            });
            /*dammu.prepare(mParser,mDanmakuContext);
            dammu.show();
            dammu.enableDanmakuDrawingCache(true);*/
        }

        //------------------------------------------------------------------------------------------------------------------
        mpresenter = new UserPersenterThree(this, new UserModelThree());
        mpresenter.getgifit();
        mpresenter.initgetv(path + "");

        recyclerthree.setLayoutManager(new MyLinearLayoutManager(getContext()));
        //自动播放
        recyclerthree.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull @NotNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE:
                        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                        MyStandardGSYVideoPlayer viewById = layoutManager.getChildAt(0).findViewById(R.id.myplayer);
                        viewById.startPlayLogic();
                        break;
                }
            }
        });

        lw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mpresenter.getgifit();
                PopupWindow popupWindow = new PopupWindow(getActivity());
                popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
                popupWindow.setHeight(800);
                View inflate1 = LayoutInflater.from(getActivity()).inflate(R.layout.act_popupwindio, null);
                popupWindow.setContentView(inflate1);

                /**
                 * SP存储
                 */

                List<User> susers = userDao.queryRaw("where userid=?", uid);
                Float fmoney = susers.get(0).getMoney();

                RecyclerView recyclerView = inflate1.findViewById(R.id.recy);
                recyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL));
                MyAdapterPopupWindio myAdapterPopupWindio = new MyAdapterPopupWindio(R.layout.item_popupwindio, data);
                recyclerView.setAdapter(myAdapterPopupWindio);
                //设置点击外部消失
                popupWindow.setOutsideTouchable(true);
                //点击事件
                myAdapterPopupWindio.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                        Float price = Float.valueOf(data.get(position).getPrice());
                        //判断用户是否登录
                        boolean isuser = user.getBoolean("isuser", false);
                        if (isuser) {
                            if (price > fmoney) {
                                ToastUtils.showShort("余额不足请充值！");
                            } else {
                                String gifImg = data.get(position).getGifImg();
                                LogUtils.i("-------------" + position);
                                threeImg.setVisibility(View.VISIBLE);
                                Glide.with(getContext()).load(gifImg).into(threeImg);
                                Timer timer = new Timer();
                                timer.schedule(new TimerTask() {
                                    @Override
                                    public void run() {
                                        getActivity().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                threeImg.setVisibility(View.GONE);
                                            }
                                        });
                                    }
                                }, 3000);
                                mpersentermoney.getmonry(uid, "-" + price);
                            }
                        } else {
                            ToastUtils.showShort("未登录,请登录");
                            Intent intent = new Intent(getContext(), LoginActivity.class);
                            getActivity().startActivity(intent);
                        }

                    }
                });
                popupWindow.showAsDropDown(lw, 0, 320);
            }
        });
    }


    private void addDanmaku(boolean islive,String s) {
        BaseDanmaku danmaku = mDanmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);
        if (danmaku == null || dammu == null) {
            return;
        }
        danmaku.text = s;
        danmaku.padding = 5;
        danmaku.priority = 8;  // 可能会被各种过滤器过滤并隐藏显示，所以提高等级
        danmaku.isLive = islive;
        danmaku.setTime(dammu.getCurrentTime() + 500);
        danmaku.textSize = 25f * (mParser.getDisplayer().getDensity() - 0.6f);
        danmaku.textColor = Color.RED;
        danmaku.textShadowColor = Color.WHITE;
        danmaku.borderColor = Color.GREEN;
        dammu.addDanmaku(danmaku);

    }
    @Override
    public void UserBean(UserBean userBean) {

    }

    @Override
    public void LogUserBean(UserBean userBean) {

    }

    //充值
    @Override
    public void MoneyUserBean(MoneyBean userBean) {
        String money = userBean.getData().getMoney() + "";
        String userName = userBean.getData().getUserName();
        String userPwd = userBean.getData().getUserPwd();
        Integer userId = userBean.getData().getUserId();
        List<User> users = userDao.queryRaw("where userid=?", uid);
        Long id = users.get(0).getId();

        float v = Float.parseFloat(money);
        LogUtils.i(money);
        //修改
        User user = new User();
        user.setId(id);
        user.setName(userName);
        user.setPass(userPwd);
        user.setUserid(userId);
        user.setMoney(v);
        userDao.update(user);
        //查询
        List<User> users2 = userDao.queryRaw("where userid=?", uid);
        LogUtils.i("支付数据库查询----" + "ID:" + users2.get(0).getId() + "--name:" + users2.get(0).getName() + "--pass:" + users2.get(0).getPass() + "--mID:" + users2.get(0).getUserid() + "--money:" + users2.get(0).getMoney());
        EventBus.getDefault().postSticky("ZFB:" + money);
    }

    @Override
    public void getImgBean(ImgBean imgBean) {

    }


    public class MyAdapterPopupWindio extends BaseQuickAdapter<PopupWindioBean.DataBean, BaseViewHolder> {

        public MyAdapterPopupWindio(int layoutResId, @Nullable List<PopupWindioBean.DataBean> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(@NotNull BaseViewHolder baseViewHolder, PopupWindioBean.DataBean dataBean) {
            Glide.with(getActivity()).load(dataBean.getPreviewImg()).into((ImageView) baseViewHolder.getView(R.id.p_img));
            baseViewHolder.setText(R.id.p_text, dataBean.getName());
            baseViewHolder.setText(R.id.p_money, dataBean.getPrice() + "");
        }
    }

    public void initvoid() {
        smart.finishRefresh();
        smart.finishLoadMore();

        if (myVodioAdapter == null) {
            myVodioAdapter = new MyVodioAdapter(R.layout.vodiothree, datavodio);
            recyclerthree.setAdapter(myVodioAdapter);
        } else {
            if (ispopu) {
                myVodioAdapter.getData().clear();
            }
            myVodioAdapter.getData().addAll(datavodio);
            myVodioAdapter.notifyDataSetChanged();
        }
    }

    //视频加载
    @Override
    public void getV(Vodiobean vidioBeam) {

        datavodio = vidioBeam.getData();
        initvoid();
    }

    @Override
    public void getGifit(PopupWindioBean popupWindioBean) {

        data = popupWindioBean.getData();

    }

    @Override
    public void initView() {
        lw = (ImageView) findViewById(R.id.lw);
        threeImg = (ImageView) findViewById(R.id.three_img);
        recyclerthree = (RecyclerView) findViewById(R.id.recyclerthree);
        smart = (SmartRefreshLayout) findViewById(R.id.smart);

        smart.setEnableRefresh(true);
        smart.setEnableLoadMore(true);

        smart.setOnRefreshListener(this);
        smart.setOnLoadMoreListener(this);
        textdm = (EditText) findViewById(R.id.textdm);
        buttondm = (Button) findViewById(R.id.buttondm);
        dammu = (DanmakuView) findViewById(R.id.dammu);
    }

    @Override
    public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
        ispopu = false;
        path++;
        mpresenter.initgetv(path + "");
    }

    @Override
    public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
        ispopu = true;
        path = 1;
        mpresenter.initgetv(path + "");
    }


    @Override
    public void showToast() {

    }

    @Override
    public void onPause() {
        super.onPause();
        GSYVideoManager.onPause();

        Log.i(TAG, "2onPause: ");
    }

    @Override
    public void onResume() {
        super.onResume();
//        GSYVideoManager.onResume();
        Log.i(TAG, "2onResume: ");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
        Log.i(TAG, "2onDestroy: ");
    }


}